/*******************************************************************************

GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

@license http://www.gnu.org/licenses/lgpl.txt

@author <elmo.dd@gmail.com>
@version 0.9

*******************************************************************************/
(function(){

  //available options
  var options = {
    url: '',
    project: '',
    caption: 'report a issue?'
  };

  //retrieve parameters
  var scripts = document.getElementsByTagName('script');
  //the script should be placed as last script in the body so let's iterate starting from the last one
  var i;
  for(i = (scripts.length - 1); i >= 0; --i) {
    if(scripts[i].src.search(/tc.js/) != -1) {
      var script = scripts[i];
      break;
    }
  }

  //parameters start after ".*tc.js?"
  var params = script.src.replace(/.*tc.js\?/, '').split('&');
  //get path to css
  var cssPath = script.src.replace(/tc\.js\?.*/, 'tc.css');
  //if the script is called localy, we do not need any paths
  if(cssPath.search(/^file:/) != -1) {
    cssPath = 'tc.css';
  }

  //match params to options 
  var paramSplit = [];
        
  for(i in params) {
    paramSplit = params[i].toString().split('=');
    //is this option available?
    if(options[paramSplit[0]] != undefined) {
      options[paramSplit[0]] = paramSplit[1];
    }
  }

  //check mandatory options
  if(options.url == '') {
    throw 'ticketConnectr: url is missing';
  }

  //prepare options
  options.url = unescape(options.url);

  if(options.project != '' && options.url.search(/#project#/) != -1) {
    options.url = options.url.replace(/#project#/, options.project);
  }

  //add style
  var styleElement = document.createElement('link');
  styleElement.rel = 'stylesheet';
  styleElement.type = 'text/css';
  styleElement.href = cssPath;

  document.getElementsByTagName('head')[0].appendChild(styleElement);

  //add elements
  var containerElement = document.createElement('div');
  containerElement.id = 'ticketConnectr';
  containerElement.style.position = 'absolute';
  containerElement.style.top = '5px';

  var linkText = document.createTextNode(options.caption);

  var linkElement = document.createElement('a');
  linkElement.target = '_blank';
  linkElement.href = options.url;
  linkElement.appendChild(linkText);

  containerElement.appendChild(linkElement);

  document.getElementsByTagName('body')[0].appendChild(containerElement);

  //add event
  document.onscroll = function(scrollEvent) {
    containerElement.style.top = (window.pageYOffset + 5) + 'px';
  };
})();
